<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 500px;
            height: 500px;
            background-color: #ff0;
            position: relative;
            margin: auto;
        }

        .a {
            width: 100px;
            height: 100px;
            background-color: #f00;
            position: absolute;
        }
    </style>
</head>

<body>

    <div class="box">
        <div class="a"></div>
    </div>



    <script>
        var oBox = document.querySelector('.box');
        var oA = document.querySelector('.a');

        // 获取元素的相关尺寸需要消耗性能    move事件是一个高频率事件
        var r = oA.offsetWidth / 2;
        var _boxLeft = oBox.offsetLeft;
        var _boxTop = oBox.offsetTop;

        var maxWidth = oBox.clientWidth - oA.offsetWidth;
        var maxHeight = oBox.clientHeight - oA.offsetWidth;

        document.onmousemove = function (e) {
            e = e || event;
            var x = e.x - r - _boxLeft;
            var y = e.y - r - _boxTop;
            if (x < 0) x = 0;
            if (y < 0) y = 0;
            if (x > maxWidth) x = maxWidth;
            if (y > maxHeight) y = maxHeight;
            oA.style.left = x + 'px';
            oA.style.top = y + 'px';
        }

    </script>

</body>

</html>